from datetime import datetime, timedelta
from email.header import Header
from email.mime.application import MIMEApplication
import mimetypes
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from ConfigManager import ConfigManager
import Logger_config

# 设置日志配置
logger = Logger_config.setup_logger()

class Email:
    def __init__(self):       
        self.cm = ConfigManager()

    def send_email(self, subject, recipients, cc_recipients, body, is_html=True):
        """
        发送邮件
        
        参数:
            subject: 邮件主题
            recipients: 收件人列表
            cc_recipients: 抄送人列表
            body: 邮件正文内容
            is_html: 是否为HTML格式，默认为True
        """
        # 邮件服务器配置
        smtp_server = self.cm.get_merged_config()['smtp']['server']  
        smtp_port = self.cm.get_merged_config()['smtp']['port']  
        smtp_user = self.cm.get_merged_config()['smtp']['user']  
        smtp_password = self.cm.get_merged_config()['smtp']['password']  

        # 创建邮件对象
        msg = MIMEMultipart()
        msg['From'] = smtp_user
        msg['To'] = ', '.join(recipients)
        msg['Cc'] = ', '.join(cc_recipients)
        msg['Subject'] = subject

        # 添加邮件正文
        msg.attach(MIMEText(body, 'html' if is_html else 'plain'))

        # 连接到SMTP服务器并发送邮件
        try:
            with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
                server.login(smtp_user, smtp_password)
                server.sendmail(smtp_user, recipients + cc_recipients, msg.as_string())
            logger.info(f"邮件发送成功：主送{recipients},抄送{cc_recipients}")
        except Exception as e:
            logger.error(f"邮件发送失败: {e}")
            raise e

    def send_email_with_attachments(self, subject, recipients, cc_recipients, html_content, image_cid_list,attachment_files_path:list=None):
        """
        发送带附件和内联图片的HTML邮件
        
        参数:
            subject (str): 邮件主题
            recipients (list[str]): 收件人邮箱地址列表
            cc_recipients (list[str]): 抄送人邮箱地址列表
            html_content (str): HTML格式的邮件正文内容
            image_cid_list (list[dict]): 内联图片信息字典列表，每个字典应包含：
                - data (bytes): 图片二进制数据
                - cid (str): 图片内容ID（用于HTML中引用）
                - mime_type (str): 图片MIME类型（如'image/png'）
            attachment_files_path (list[str], optional): 附件文件路径列表
        
        异常:
            RuntimeError: 当邮件发送失败时抛出，包含错误详细信息
        
        功能说明:
            1. 创建MIMEMultipart邮件对象
            2. 添加HTML正文内容（自动设置UTF-8编码）
            3. 嵌入内联图片（通过Content-ID引用）
            4. 添加普通文件附件
            5. 使用SMTP_SSL安全连接发送邮件
        """
        try:
            # 邮件服务器配置
            smtp_server = self.cm.get_merged_config()['smtp']['server']  
            smtp_port = self.cm.get_merged_config()['smtp']['port']  
            smtp_user = self.cm.get_merged_config()['smtp']['user']  
            smtp_password = self.cm.get_merged_config()['smtp']['password']  

            msg = MIMEMultipart('related')
            msg['From'] = self.smtp_user
            msg['To'] = ', '.join(recipients)
            msg['Cc'] = ', '.join(cc_recipients)
            msg['Subject'] = subject

            part = MIMEText(html_content, 'html', 'utf-8')
            msg.attach(part)

            for img_info in image_cid_list:
                img_data = img_info['data']  # bytes 类型，来自 WordContentExtractor 提供的数据
                subtype = img_info['mime_type'].split('/')[1]
                msg_img = MIMEImage(img_data, subtype=subtype)
                msg_img.add_header('Content-ID', f"<{img_info['cid']}>")
                msg_img.add_header('Content-Disposition', 'inline')
                msg.attach(msg_img)

            # 添加普通附件
            if attachment_files_path is not None:
                for file_path in attachment_files_path:
                    with open(file_path, 'rb') as f:
                        file_data = f.read()
                    file_name = os.path.basename(file_path)

                    # 获取文件的 MIME 类型
                    content_type, _ = mimetypes.guess_type(file_path)
                    maintype, subtype = content_type.split('/') if content_type else ('application', 'octet-stream')                    
                    file_part = MIMEApplication(file_data, _subtype=subtype)
                    filename_header = Header(file_name, 'utf-8').encode()
                    file_part.add_header('Content-Disposition', 'attachment', filename=filename_header)
                    msg.attach(file_part)
                    
            with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
                server.login(smtp_user, smtp_password)
                server.sendmail(smtp_user, recipients + cc_recipients, msg.as_string())
                logger.info(f"邮件发送成功：主送{recipients},抄送{cc_recipients}")
        except Exception as e:
            raise RuntimeError(f"邮件发送失败: {e}")

if __name__ == "__main__":
    # 获取当前日期
    today = datetime.now()

    # 计算本周一的日期
    start_of_week = today - timedelta(days=today.weekday())
    friday_of_week = start_of_week + timedelta(days=4)

    # 格式化日期为YYYY/MM/DD
    start_of_week_formatted = start_of_week.strftime('%Y/%m/%d')
    friday_of_week_formatted = friday_of_week.strftime('%Y/%m/%d')

    # 邮件内容（HTML格式）
    body = f"""
    <html>
    <body style="font-family: 'Microsoft YaHei', sans-serif; font-size: 14pt; background-color: white;">
        <p>各位老师好：</p>
        <p>本次简讯时间范围：{start_of_week_formatted}-{friday_of_week_formatted}。<span style="background-color: lightgreen;">请于{friday_of_week_formatted} 19点前反馈</span>，过时截止收集。</p>
        <p>具体的填写要求见参考示例，每条50字以内，凸显重点，请各位同事引起重视。</p>
        <p>反馈链接：<a href="https://docs.qq.com/doc/DTXJZTUxwbVhJVkZu">https://docs.qq.com/doc/DTXJZTUxwbVhJVkZu</a></p>
        <p>注：<br>
        Word简讯：方便部门全员了解部门整体各项重要活动，各组每周市场拓展、奖项荣誉等动态工作进展；邮件发送全体同事。</p>
    </body>
    </html>
    """
    subject = f"{start_of_week_formatted} 19点前反馈-请在各组范围内填写-填写后内容标黑删除提示内容"

    recipients = [
        "chengyuansen@cmsr.chinamobile.com"
    ]
    cc_recipients = [
    ]

    notificationEmail = Email()
    # 发送邮件
    notificationEmail.send_email(subject, recipients, cc_recipients, body)